# Homework 1
# Simulation of Simmon's Situation B
# Nichole Hanus
# Due 3/31/15



# Develop a function for SituationB that asks for significance level as input
SituationB <- function(sig.level){
  
# Set the number of trials for simulation  
Trials <- 15000


# Define counter used to calculate false positive rates 
a <- 0

# Define counter used for the number of Trials
i <- 0

# Start the While loop for the total number of assigned simulations (trials)
while( i < Trials){
  obs <- 20
  
  x <- rnorm(obs, 0, 1) # Generate normal RV with mean = 0, var = 1
  y <- rnorm(obs, 0, 1)

# Two-sample t-test
  ttest <- t.test(x, y, var.equal = TRUE)

# Determine p-value from t-test
  p_value <- ttest$p.value

  
# Determine if p-value is significant
# If significant, increase the false-positive rate counter
  if (p_value < sig.level){a <- a+1}

#If p-value is not significant, try again w/ 10 more observations             
             else{
               obs <- 10
               
               x <- c(x,rnorm(obs, 0, 1)) # Adds the 10 new normal RV to x vector
               y <- c(y,rnorm(obs, 0, 1)) # Adds the 10 new nomral RV to y vector
               
               ttest <- t.test(x, y, var.equal = TRUE) # Performs two-sample t-test again
               
               p_value <- ttest$p.value # Determines p-value again
               
               if (p_value < sig.level){a <- a+1} # Increase counter if significant
               
             }
  i = i +1 # Increase Trial counter after each iteration
}

#Calculates the significant p-values that arose in the simulation
P.value.percentage <- (a/Trials)


return(P.value.percentage)}

p.value.inputs <- c(.1, .05, .01) # Creates vector of significant level inputs

# sapply runs the SituationB function using the vector of sig level inputs
# sapply then saves function outputs into False.Positive.Rates vector
False.Positive.Rates <- round(sapply(p.value.inputs,SituationB),3)

# Creates data frame of Significant Level headers and simulation results
DF <- data.frame(P.values = c(".1",".05",".01"), False.Positive.Rates)
DF
